﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Young3.FMSearch.Business.Entities.Cache;
using System.Reflection;
using System.Collections;
using Young3.FMSearch.Business.Entities.InGame;
using System.Diagnostics;

namespace Young3.FMSearch.Business.Managers
{
    public class CacheManager
    {
        public List<CacheItem> Items { get; set; }


        public void FillCache(ObjectManager objectManager)
        {
            Items = new List<CacheItem>();

            foreach (PropertyInfo pinf in objectManager.GetType().GetProperties())
            {
                if (typeof(IList).IsAssignableFrom(pinf.PropertyType))
                {
                    int counter = 0;
                    Stopwatch sw = new Stopwatch();
                    sw.Start();

                    IList curList = (IList)pinf.GetValue(objectManager, null);
                    PropertyInfo[] entityProps = pinf.PropertyType.GetGenericArguments()[0].GetProperties();
                    Type entityType =pinf.PropertyType.GetGenericArguments()[0];

                    foreach (object item in curList)
                    {
                        counter++;
                        if (counter % 1000 == 0)
                        {
                            sw.Stop();
                            sw.Reset();
                            sw.Start();
                        }

                        BaseObject ingameEntity = (BaseObject)item;

                        CacheItem cachedItem = new CacheItem()
                        {
                             MemoryAddress = ingameEntity.MemoryAddress,
                             Type = entityType,
                             Properties = new Dictionary<string,object>()
                        };

                        foreach (PropertyInfo entityPropInfo in entityProps)
                        {
                            cachedItem.Properties.Add(entityPropInfo.Name, (object)entityPropInfo.GetValue(ingameEntity, null));
                        }

                        Items.Add(cachedItem);
                    }
                }
            }
        }

    }
}
